package com.example.passwordmanager.dialog;

import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.example.passwordmanager.R;
import com.example.passwordmanager.Util.FingerprintUtil;

public class FingerprintDialogFragment extends BaseDialogFragment{
    private CallBack callBack;

    public FingerprintDialogFragment(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected int getViewLayoutId() {
        return R.layout.dialog_fingerprint;
    }

    private FingerprintManager.AuthenticationCallback authenticationCallback=new FingerprintManager.AuthenticationCallback() {
        @Override
        public void onAuthenticationError(int errorCode, CharSequence errString) {
            super.onAuthenticationError(errorCode, errString);
        }

        @Override
        public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
            super.onAuthenticationHelp(helpCode, helpString);
        }

        @Override
        public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
            super.onAuthenticationSucceeded(result);
            callBack.onSucceed();
            dismiss();
        }

        @Override
        public void onAuthenticationFailed() {
            super.onAuthenticationFailed();
            textView.setText("验证失败,再试一次。");
        }
    };
    private TextView textView,tv_cancel;
    private FingerprintUtil fingerprintUtil;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void initView(View view) {
          textView=view.findViewById(R.id.tv_tip);
          tv_cancel=view.findViewById(R.id.tv_cancel);
          tv_cancel.setOnClickListener(v->{
              dismiss();
          });

          fingerprintUtil=new FingerprintUtil(getContext());
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onStart() {
        super.onStart();
        fingerprintUtil.startListening(authenticationCallback);
        Window window = getDialog().getWindow();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
//        p.height = (int) (d.getHeight() * 0.6); // 高度设置为屏幕的0.6，根据实际情况调整
        p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65，根据实际情况调整
        window.setAttributes(p);
    }

    @Override
    public void onStop() {
        super.onStop();
        fingerprintUtil.stopListening();
    }

    public interface CallBack{
        void onSucceed();

    }
}
